What is load-json-file?
The 'load-json-file' npm package is a utility that allows for easy reading and parsing of JSON files in Node.js. It simplifies the process of loading JSON data from files, handling potential errors, and converting the JSON string into a JavaScript object.
What are load-json-file's main functionalities?
Load JSON file
This feature allows you to asynchronously load and parse a JSON file, returning a promise that resolves with the parsed JSON object.
const loadJsonFile = require('load-json-file');
loadJsonFile('foo.json').then(json => {
console.log(json);
}).catch(error => {
console.error('Error loading JSON file:', error);
});
Synchronous JSON file loading
This feature provides a synchronous method to load and parse a JSON file, useful when you need to load JSON data at the start of an application or in a synchronous script.
const loadJsonFile = require('load-json-file');
try {
const json = loadJsonFile.sync('foo.json');
console.log(json);
} catch (error) {
console.error('Error loading JSON file:', error);
}
Other packages similar to load-json-file
jsonfile
Similar to 'load-json-file', 'jsonfile' offers APIs to read and write JSON files. It provides both asynchronous and synchronous methods but has additional write capabilities, making it more versatile if modification of JSON files is required.
fs-extra
While 'fs-extra' extends the native 'fs' module and includes all its methods, it also adds file operation methods not found in the standard library. It supports JSON file operations similar to 'load-json-file' but is more comprehensive in terms of general file handling capabilities.
load-json-file
Read and parse a JSON file
Strips UTF-8 BOM, uses graceful-fs
, and throws more helpful JSON errors.
Install
$ npm install load-json-file
Usage
const loadJsonFile = require('load-json-file');
loadJsonFile('foo.json').then(json => {
console.log(json);
});
API
loadJsonFile(filePath, [options])
Returns a promise for the parsed JSON.
loadJsonFile.sync(filepath, [options])
Returns the parsed JSON.
options
Type: Object
beforeParse
Type: Function
Applies a function to the JSON string before parsing.
reviver
Type: Function
Prescribes how the value originally produced by parsing is transformed, before being returned. See the JSON.parse
docs for more.
Related
License
MIT © Sindre Sorhus